using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using NewtonDynamics;

namespace WPFPhysics1
{
	/// <summary>
	/// Interaction logic for World.xaml
	/// </summary>

	public partial class World : UserControl, INotifyPropertyChanged
	{
		public World()
		{
			InitializeComponent();

			CompositionTarget.Rendering += new EventHandler( CompositionTarget_Rendering );
			base.SizeChanged += new SizeChangedEventHandler( World_SizeChanged );
		}

		/// <summary>
		/// Frame rendering event
		/// </summary>
		/// <param name="sender">Sender</param>
		/// <param name="e">Event arguments</param>
		void CompositionTarget_Rendering( object sender, EventArgs e )
		{
			Bodies bodies = DataContext as Bodies;
			if ( bodies != null ) bodies.Update();
		}

		/// <summary>
		/// Size changed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void World_SizeChanged( object sender, SizeChangedEventArgs e )
		{
			if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "ScaleTransform" ) );
		}

		/// <summary>
		/// Get scale transformation
		/// </summary>
		public System.Windows.Media.Matrix ScaleTransform
		{
			get
			{
				Bodies bodies = DataContext as Bodies;

				if ( bodies != null )
				{
					double height = ActualHeight;
					double width = height * ( bodies.WorldWidth / bodies.WorldHeight );

					Matrix matrix = Matrix.Identity;

					// Scale world units to display units
					matrix.Scale( width / bodies.WorldWidth, height / bodies.WorldHeight );

					// Adjust for aspect ratio (center appropriately)
					matrix.Translate( ( ActualWidth - width ) / 2, ( ActualHeight - height ) / 2 );

					// Center on display
					matrix.Translate( width / 2, height / 2 );

					return matrix;
				}

				return Matrix.Identity;
			}
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		#endregion
	}
}